<?php
namespace app\im\controller;

use app\card\model\UserInfo;
use app\material\model\BrochureIm;
use app\material\model\ImVideo;
use app\shop\model\IndexUser;
use Redis;
use think\facade\Cache;
use think\facade\Config;

class Some  {


    public $redis;

    public function __construct() {

        $host =  Config::get('cache.stores.redis.host');

        $port =  Config::get('cache.stores.redis.port');

        $password =  Config::get('cache.stores.redis.password');

        if(empty($this->redis)||$this->redis->ping()!=true){

            $this->redis = new Redis();

            $this->redis->connect($host,$port);

            if(!empty($password)){

                $this->redis->auth($password); //设置密码
            }

//            $connect_status = $this->redis->ping();

//        if($connect_status != "+PONG")
//            if($connect_status != true)
//            {
//                $this->redis->connect($host,$port);
//
//                if(!empty($password)){
//
//                    $this->redis->auth($password); //设置密码
//                }
//
//            }

        }

    }

    /**
     * @param $ws
     * @param $request
     * @功能说明:建立连接回调(智能物料)
     * @author chenniang
     * @DataTime: 2021-07-02 18:17
     */
    public function mOnOpen($data,$fd) {

        $room_key = $data['room_key'];

        $uid      = !empty($data['user_id'])?$data['user_id']:0;

        $target_id= !empty($data['target_id'])?$data['target_id']:0;

        $uniacid  = !empty($data['uniacid'])?$data['uniacid']:0;
        //是否是群主
        $leader   =!empty($data['presenter'])?$data['presenter']:0;
        //1是文件 2是宣传册
        $type     = !empty($data['type'])?$data['type']:1;
        //加入房间域
        $this->redis->hset($room_key,$uid,$fd);
        //加入组集合
        $this->redis->sadd('group', $room_key);
        //如果是群主
        if($leader==1){

            $key = $room_key.'-leader';
            //群主
            $this->redis->set($key,$uid,86400);

        }

        $bIm_model = new BrochureIm();

        $dis = [

            'user_id'     => $uid,

            'room_key'    => $room_key,

            'brochure_id' => $target_id,

            'type'        => $type,
        ];

        $find = $bIm_model->dataInfo($dis);

        $room_status = $bIm_model->where(['room_key'=>$room_key,'leader'=>1])->value('status');

        $room_status = !empty($room_status)?$room_status:1;

        if(empty($find)){

            $key     = $room_key.'-leader';
            //群主
            $user_id = $this->redis->get($key);

            $user_info = new UserInfo();

            $user_id = !empty($user_id)?$user_id:0;

            $company_id = $user_info->where(['fans_id'=>$user_id])->value('company_id');

            $insert = [

                'uniacid'     => $uniacid,

                'user_id'     => $uid,

                'room_key'    => $room_key,

                'brochure_id' => $target_id,

                'leader'      => $leader,

                'type'        => $type,

                'company_id'  => !empty($company_id)?$company_id:0,

                'status'      => $room_status

            ];

            $bIm_model->dataAdd($insert);
        }else{

            $bIm_model->dataUpdate($dis,['status'=>$room_status]);

        }

    }


    /**
     * @param $ws
     * @param $frame
     * @功能说明:接受消息回调(智能物料)
     * @author chenniang
     * @DataTime: 2021-07-02 18:17
     */
    public function mOnMessage($ws, $data,$fd) {

        $room_key = $data['data']['room_key'];
        //获取房间
        $room = $this->redis->hGetAll($room_key);

        if(!empty($room)){

            foreach ($room as $k => $vv) {
                //投递消息
                $ws->push($vv, json_encode($data));

            }

        }

    }


    /**
     * @param $ws
     * @param $data
     * @param $fd
     * @功能说明:保存音频
     * @author chenniang
     * @DataTime: 2021-08-10 17:25
     */
    public function addVideo($ws, $data,$fd){

        $room_key = $data['data']['room_key'];

        $uniacid  = !empty($data['data']['uniacid'])?$data['data']['uniacid']:0;

        $video    = FILE_UPLOAD_PATH.$data['data']['video'];

        if(!empty($data['data']['video'])){

            $im_video_model = new ImVideo();

            $insert = [

                'uniacid' => $uniacid,

                'room_key' => $room_key,

                'video'    => $video,

            ];

            $im_video_model->dataAdd($insert);

        }

    }



    /**
     * @param $ws
     * @param $frame
     * @功能说明:接受消息回调(智能物料)
     * @author chenniang
     * @DataTime: 2021-07-02 18:17
     */
    public function onLogin($ws, $data,$fd) {

        $room_key = $data['data']['room_key'];

//        $room_key = '20210802093606035000000350';
        //获取房间
        $room = $this->redis->hgetall($room_key);

        if(!empty($room)){

            $user_model = new IndexUser();

            $bIm_model  = new BrochureIm();

            $user_id = array_keys($room);

            $key = $room_key.'-leader';
            //获取群组的用户id
            $leader_id = $this->redis->get($key);

            if(!empty($leader_id)){

                $user_key = array_search($leader_id,$user_id);

                if(is_numeric($user_key)&&array_key_exists($user_key,$user_id)){

                    unset($user_id[$user_key]);
                }

            }

            $user = $user_model->where('id','in',$user_id)->field('nickName,avatarUrl')->select()->toArray();

            $list['data']['user']     = $user;

            $list['action']           = $data['action'];

            $list['data']['room_key'] = $room_key;

            $list['data']['count']    = count($user_id);

            $dis = [

                'room_key' => $room_key,

                'leader'   => 1
            ];
            //演示状态
            $list['data']['is_start'] = $bIm_model->where($dis)->value('status');

            foreach ($room as $k => $vv) {
                //投递消息
                $ws->push($vv, json_encode($list));

            }

        }


    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-28 16:50
     * @功能说明:开始演示
     */
    public function startAction($ws, $data,$fd){

        $room_key = $data['data']['room_key'];

        $bIm_model = new BrochureIm();

        $dis = [

            'room_key' => $room_key,

//            'leader'   => 1
        ];
        //修改演示状态
        $bIm_model->dataUpdate($dis,['status'=>2]);

        $bIm_model->dataUpdate(['room_key'=>$room_key],['time_long'=>0,'update_time'=>time()]);

        $room = $this->redis->hGetAll($room_key);

        $list['data']['is_start'] = 2;

        $list['data']['room_key'] = $room_key;

        $list['action']           = $data['action'];

        if(!empty($room)){

            foreach ($room as $k=>$vv){
                //投递消息
                $ws->push($vv, json_encode($list));
            }

        }

    }


    /**
     * @param $serv
     * @param $task_id
     * @param $worker_id
     * @param $data
     * @功能说明:完成异步任务回调
     * @author chenniang
     * @DataTime: 2021-07-02 18:17
     */
    public function onTask($serv, $task_id, $worker_id, $data) {

        //返回字符串给worker进程——>触发onFinish
        return "success";
    }


    /**
     * @param $serv
     * @param $task_id
     * @param $data
     * @功能说明:完成任务投递回调
     * @author chenniang
     * @DataTime: 2021-07-02 18:16
     */
    public function onFinish($serv, $task_id, $data) {
        //task_worker进程将任务处理结果发送给worker进程
        echo "完成任务{$task_id}投递 处理结果：{$data}";
    }


    /**
     * @param $ws
     * @param $fd
     * @功能说明:关闭连接回调
     * @author chenniang
     * @DataTime: 2021-07-02 18:16
     */
    public function onClose($ws, $fd) {
        //退出并删除多余的分组fd
        $group = $this->redis->sMembers('group');

        foreach ($group as $v) {

            $fangjian = $this->redis->hgetall($v);

            foreach ($fangjian as $k => $vv) {

                if ($fd == $vv) {

                    $this->redis->hdel($v, $vv);

                }
            }
        }
//        echo "{$fd}关闭了连接1";
    }


    /**
     * @param $ws
     * @param $fd
     * @功能说明:解散群
     * @author chenniang
     * @DataTime: 2021-07-27 18:04
     */
    public function allLoginOut($ws,$data,$fd){

        $room_key = $data['data']['room_key'];

        $fangjian = $this->redis->hgetall($room_key);

        $im_model = new BrochureIm();

        $data['action'] = 'mOnMessage';

        $data['data']['message_type'] = 2;
        //给剩下的人发消息
        $this->mOnMessage($ws,$data,$fd);

        $bIm_model = new BrochureIm();

        $dis = [

            'room_key' => $room_key,

        ];
        //修改演示状态
        $bIm_model->where($dis)->update(['status'=>3]);

        if(!empty($fangjian)){

            foreach ($fangjian as $k => $vv) {

                $this->redis->Hdel($room_key,$k);

                $dis = [

                    'user_id' => $k,

                    'room_key'=> $room_key
                ];

                $find = $im_model->dataInfo($dis);

                if(!empty($find)&&$find['status']>1){

                    $time_long = time()-$find['update_time'];

                    $im_model->dataUpdate($dis,['time_long'=>$time_long+$find['time_long']]);

                }

            }
            //删除房间
            @$this->redis->sRem('group',$room_key);
        }


//        if(!empty($data['data']['url'])){
//
//            $url      = $data['data']['url'];
//            //合并录音
//            $im_model->addAudio($room_key,$url);
//        }


    }

    /**
     * @param $ws
     * @param $fd
     * @功能说明:退出
     * @author chenniang
     * @DataTime: 2021-07-23 17:44
     */
    public function loginOut($ws, $fd){

        $im_model = new BrochureIm();
        //退出并删除多余的分组fd
        $group = $this->redis->sMembers('group');

        if(!empty($group)){

            foreach ($group as $v) {

                $fangjian = $this->redis->hgetall($v);

                $data['data']['room_key'] = $v;

                if(!empty($fangjian)){

                    foreach ($fangjian as $k => $vv) {

                        if ($fd == $vv) {

                            $this->redis->Hdel($v,$k);

                            $dis = [

                                'user_id' => $k,

                                'room_key'=> $v
                            ];

                            $find = $im_model->dataInfo($dis);

                            if(!empty($find)&&$find['status']>1){

                                $time_long = time()-$find['update_time'];

                                $im_model->dataUpdate($dis,['time_long'=>$time_long+$find['time_long']]);

                            }

                            $data['action'] = 'onLogin';
                            //给剩下的人发消息
                            $this->onLogin($ws,$data,$fd);

                        }

                    }

                }else{

                    @$this->redis->sRem('group',$v);
                }


            }

        }




    }



    /**
     * @param $ws
     * @param $fd
     * @功能说明:退出
     * @author chenniang
     * @DataTime: 2021-07-23 17:44
     */
    public function loginOutV2($ws, $fd){

        $im_model = new BrochureIm();
        //退出并删除多余的分组fd
        $group = $this->redis->sMembers('group');

        foreach ($group as $v) {

            $fangjian = $this->redis->hgetall($v);

            $key = $v.'-leader';
            //获取群组的用户id
            $leader_id = $this->redis->get($key);
            //当前用户的id
            $user_id = array_search($fd,$fangjian);
            //如果是群组则全部退出
            $is_all  = !empty($user_id)&&$leader_id==$user_id?1:0;

            $data['data']['room_key'] = $v;
            //修改房间状态
            if($is_all==1){

                $start_key = $v.'-is_start';

                $this->redis->set($start_key,0);

                $data['action'] = 'mOnMessage';

                $data['data']['message_type'] = 2;
                //给剩下的人发消息
                $this->mOnMessage($ws,$data,$fd);

            }

            if(!empty($fangjian)){

                foreach ($fangjian as $k => $vv) {

                    if ($fd == $vv||$is_all==1) {

                        $this->redis->hdel($v, $k);


                        $dis = [

                            'user_id' => $k,

                            'room_key'=> $v
                        ];

                        $find = $im_model->dataInfo($dis);

                        if(!empty($find)){

                            $time_long = time()-$find['update_time'];

                            $im_model->dataUpdate($dis,['time_long'=>$time_long+$find['time_long']]);

                        }

                    }

                }

            }else{

                @$this->redis->sRem('group',$v);

            }
            //如果是群主断开链接
            if($is_all==0){

                $data['action'] = 'onLogin';
                //给剩下的人发消息
                $this->onLogin($ws,$data,$fd);

            }

        }

    }

}

